from fastapi import HTTPException, status
from app.models.job import Job, ParticipateJob
from app.schemas.job import AuditInDB
from app.schemas.user import JobBase, JobInDB, JobUpdate, UserInDB


async def create_job(job_data: JobUpdate) -> Job:
    try:
        job = await Job.create(
            creator_id=job_data.creator_id,
            job_name=job_data.job_name,
            company=job_data.company,
            company_size=job_data.company_size,
            salary=job_data.salary,
            detail=job_data.detail,
            head=job_data.head,
            posts=job_data.posts,
            company_address=job_data.company_address,
            company_industry=job_data.company_industry,
            company_email=job_data.company_email,
            avatar=job_data.avatar  # Add avatar field to handle validation requirement
        )
        return job
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建工作失败: {str(e)}"
        )

async def update_job(job_id: int, job_data: JobBase) -> Job:
    """
    更新工作职位信息
    
    参数:
    - job_id: int, 要更新的工作ID
    - job_data: JobBase, 包含更新后的工作信息
    
    返回:
    - Job: 更新后的工作对象
    
    异常:
    - 404 Not Found: 如果工作不存在时抛出
    - 500 Internal Server Error: 如果更新失败时抛出
    """
    job = await Job.get_or_none(job_id=job_id)  # 将 id 改为 job_id
    if not job:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="工作不存在"
        )
    
    try:
        await job.update_from_dict(job_data.model_dump())
        await job.save()
        return job
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新工作失败: {str(e)}"
        )


        
async def get_job_participants(job_id: int) -> list[ParticipateJob]:
    """
    通过job_id获取参与该岗位的所有用户信息
    
    参数:
    - job_id: int, 岗位ID
    
    返回:
    - list[ParticipateJob]: 参与该岗位的用户列表
    
    异常:
    - 404 Not Found: 如果岗位不存在时抛出
    - 500 Internal Server Error: 如果查询失败时抛出
    """
    job = await Job.get_or_none(job_id=job_id)
    if not job:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="岗位不存在"
        )
    
    try:
        participants = await ParticipateJob.filter(job_id=job_id).prefetch_related('user', 'job')
        if not participants:
            return []
        return [
            AuditInDB(
                id=participant.id,
                job=JobInDB.model_validate(participant.job.__dict__),
                user=UserInDB.model_validate(participant.user.__dict__),
                audit=participant.audit
            )
            for participant in participants
        ]
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取参与用户失败: {str(e)}"
        )


async def update_participant_audit(participant_id: int, audit_status: int) -> AuditInDB:
    """
    修改参与工作的审核状态
    
    参数:
    - participant_id: int, 参与记录ID
    - audit_status: int, 审核状态(1:审核中 2:未通过 3:通过)
    
    返回:
    - AuditInDB: 更新后的审核记录
    
    异常:
    - 404 Not Found: 如果参与记录不存在时抛出
    - 500 Internal Server Error: 如果更新失败时抛出
    """
    participant = await ParticipateJob.get_or_none(id=participant_id).prefetch_related('user', 'job')
    if not participant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="参与记录不存在"
        )
    
    try:
        participant.audit = audit_status
        await participant.save()
        return AuditInDB(
            id=participant.id,
            job=JobInDB.model_validate(participant.job.__dict__),
            user=UserInDB.model_validate(participant.user.__dict__),
            audit=participant.audit
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新审核状态失败: {str(e)}"
        )
